package it.unina.lab.parsing;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import diuf.diva.hephaistk.fusion.model.ContextHL;
import diuf.diva.hephaistk.fusion.model.ResultHL;
import diuf.diva.hephaistk.fusion.model.TransitionHL;

public class HandlerParsingContexts extends DefaultHandler {

	
	//private List<ContextHL> contesti = new ArrayList<ContextHL>();
	private ContextHL newContext = null;
	private TransitionHL newTransition = null;
	boolean passed_triggers_block = false;
	private HashMap<String,ContextHL> mappaContesti = null; 
	private Logger logger = Logger.getLogger(HandlerParsingContexts.class);
	
	
	
	public HandlerParsingContexts(HashMap<String,ContextHL> mappa){
		this.mappaContesti = mappa;
	}
	
	
	@Override
	public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
	
		if (qName.equalsIgnoreCase("context")) {
			logger.debug("Start Element :" + qName);
			newContext = new ContextHL(attributes.getValue("name"));
		}
		
		if (qName.equalsIgnoreCase("transition")) {
			logger.debug("Start Element :" + qName);
			newTransition = new TransitionHL();
		}
		
		if (qName.equalsIgnoreCase("par_or")) {
			logger.debug("Start Element :" + qName);
			newTransition.getFusionModule().add(TransitionHL.PAR_OR_START);
		}
		
		if (qName.equalsIgnoreCase("seq_and")) {
			logger.debug("Start Element :" + qName);
			newTransition.getFusionModule().add(TransitionHL.SEQ_AND_START);
		}
		
		if (qName.equalsIgnoreCase("result")) {
			logger.debug("Start Element :" + qName);
			newTransition.setResult(new ResultHL(attributes.getValue("context"), attributes.getValue("action")));
		}
		
		if (qName.equalsIgnoreCase("trigger") && passed_triggers_block) {
			logger.debug("Start Element :" + qName);
			newTransition.getFusionModule().add(attributes.getValue("name"));
		}
		
	
	
	}

	
	@Override
	public void endElement(String uri, String localName,String qName) throws SAXException {
	
		if (qName.equalsIgnoreCase("context")) {
			logger.debug("End Element :" + qName);
			mappaContesti.put(newContext.getName(),newContext);
		}
		
		if (qName.equalsIgnoreCase("transition")) {
			logger.debug("End Element :" + qName);
			newContext.addTransition(newTransition);
		}
		
		if (qName.equalsIgnoreCase("par_or")) {
			logger.debug("End Element :" + qName);
			newTransition.getFusionModule().add(TransitionHL.PAR_OR_END);
		}
		
		if (qName.equalsIgnoreCase("seq_and")) {
			logger.debug("End Element :" + qName);
			newTransition.getFusionModule().add(TransitionHL.SEQ_AND_END);
		}
		
		if (qName.equalsIgnoreCase("triggers")) {
			logger.debug("End Element :" + qName);
			passed_triggers_block = true;
		}	
		
	
	}	
	

}
